package com.boyuan.huijiaoyu;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.EMCallBack;
import com.easemob.EMValueCallBack;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMGroupManager;
import com.easemob.util.EMLog;
import com.easemob.util.HanziToPinyin;
import com.example.contactfragment.ContactService;
import com.example.contactfragment.HomeContactOrgActivity;
import com.example.huanxin.ChatActivity;
import com.example.huanxin.Constant;
import com.example.huanxin.more.HXSDKHelper;
import com.example.huanxin.more.User2;
import com.example.huanxin.more.UserDao;
import com.example.newfragment.DetailPerson;
import com.example.newfragment.RecentPerson;
import com.magicsoft.app.helper.ToastHelper;
import com.magicsoft.app.wcf.listener.GetOneRecordListener;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

public class HomeContactDeail2Activity extends BaseActivity implements
		OnClickListener {

	private DetailPerson homeContactDetailEntity;
	private TextView tv_name;
	private boolean progressShow;
	private String uid;
	private String yonghuID;
	private ContactService contactService;
	private TextView tv_mobile;
	private TextView tv_bumen;
	private TextView tv_job;
	private TextView tv_sex;
	String realname;
	private String mobile;
	private ImageView imag_touxiang;
	private DisplayImageOptions options;
	private ImageLoader imageLoader;
	private CloseContactDeatil closeContactDeatil;
	private ImageView imag_sex;
	private String titleback;
	private TextView tv_titleback;
	private ImageView imag_xingbiao;
	private String familyid;
	private String familyname;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_home_contact_deail2);
		SharedPreferences sp = getSharedPreferences("a.xml", 0);
		yonghuID = sp.getString("id", "");
//		familyid = sp.getString("familyid", "");
//		familyname = sp.getString("familyname", "");
		Intent intent = getIntent();
		titleback = intent.getStringExtra("titleback");
		uid = intent.getStringExtra("uid");
		homeContactDetailEntity = (DetailPerson) intent.getSerializableExtra("homeContactDetailEntity");
		realname = homeContactDetailEntity.getRealname();
		mobile = homeContactDetailEntity.getMobile();
		familyid = homeContactDetailEntity.getFamily_id();
		familyname = homeContactDetailEntity.getFamily_name();
		initUI();
//		getContactDetail(uid);
//		registClosecontactDeatilRecive();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
//		unregisterReceiver(closeContactDeatil);
	}

	private void initUI() {
		imageLoader = ImageLoader.getInstance();
		tv_name = (TextView) findViewById(R.id.tv_name);
		tv_sex = (TextView) findViewById(R.id.tv_sex);
		tv_mobile = (TextView) findViewById(R.id.tv_mobile);
		tv_bumen = (TextView) findViewById(R.id.tv_department);
		tv_job = (TextView) findViewById(R.id.tv_job);
		tv_titleback = (TextView) findViewById(R.id.tv_back_txt2);
		tv_titleback.setText(titleback);
		findViewById(R.id.lin_back).setOnClickListener(this);
		findViewById(R.id.ivbtn_sms).setOnClickListener(this);
		findViewById(R.id.lay_tel).setOnClickListener(this);
		findViewById(R.id.btn_liaotian).setOnClickListener(this);
		RelativeLayout lay_bumen = (RelativeLayout) findViewById(R.id.lay_mybumen);
		lay_bumen.setOnClickListener(this);
		RelativeLayout lay_setxingbiao = (RelativeLayout) findViewById(R.id.lay_setxinbiao);
		lay_setxingbiao.setOnClickListener(this);
		imag_xingbiao = (ImageView) findViewById(R.id.image_xingbiao);
		imag_touxiang = (ImageView) findViewById(R.id.imageview001);
		imag_touxiang.setOnClickListener(this);
		options = new DisplayImageOptions.Builder()
				.showImageOnLoading(R.drawable.default_header)
				.showImageForEmptyUri(R.drawable.default_header)
				.showImageOnFail(R.drawable.default_header).cacheInMemory(true)
				.cacheOnDisc(true).considerExifParams(true).build();
		imag_sex = (ImageView) findViewById(R.id.iv_gender1);
		
		if("1".equals(homeContactDetailEntity.getIs_favorite())){
			imag_xingbiao.setSelected(true);
		}else{
			imag_xingbiao.setSelected(false);
		}
		tv_name.setText(realname);
		tv_sex.setText(homeContactDetailEntity.getSex());
		if("男".equals(homeContactDetailEntity.getSex())){
			imag_sex.setBackgroundResource(R.drawable.img_male);
		}else{
			imag_sex.setBackgroundResource(R.drawable.img_female);
		}
		tv_mobile.setText(mobile);
		tv_bumen.setText(homeContactDetailEntity.getFamily_name());
		if("".equals(homeContactDetailEntity.getJob_name())){
			tv_job.setText("暂无职位");
		}else{
			tv_job.setVisibility(View.VISIBLE);
			tv_job.setText(homeContactDetailEntity.getJob_name());
		}
		String uri = homeContactDetailEntity.getAvatar();
		imageLoader.displayImage(uri, imag_touxiang, options);
	}

	public void registClosecontactDeatilRecive() {
		closeContactDeatil = new CloseContactDeatil();
		IntentFilter filter = new IntentFilter();
		filter.addAction("CloseContactDetail");
		registerReceiver(closeContactDeatil, filter);
	}

	class CloseContactDeatil extends BroadcastReceiver {

		@Override
		public void onReceive(Context arg0, Intent arg1) {
			finish();
		}

	}

//	private void getContactDetail(String contactsID) {
//
//		if (contactService == null) {
//			contactService = new ContactService(getApplicationContext());
//		}
//		
//		showLoading(getString(R.string.loading_data));
//		
//		contactService.getContactdetail(yonghuID, uid,
//				new GetOneRecordListener<DetailPerson>() {
//
//					@Override
//					public void onFinish(DetailPerson data) {
//						hideLoading();
//						homeContactDetailEntity = data;
//						account = homeContactDetailEntity.getAccount();
//						realname = homeContactDetailEntity.getRealname();
//						mobile = homeContactDetailEntity.getMobile();
//						familyid = homeContactDetailEntity.getFamily_id();
//						familyname = homeContactDetailEntity.getFamily_name();
//						String is_favorite = homeContactDetailEntity.getIs_favorite();
//						if("1".equals(is_favorite)){
//							imag_xingbiao.setSelected(true);
//						}else{
//							imag_xingbiao.setSelected(false);
//						}
//						tv_name.setText(realname);
//						tv_sex.setText(homeContactDetailEntity.getSex());
//						if("男".equals(homeContactDetailEntity.getSex())){
//							imag_sex.setBackgroundResource(R.drawable.img_male);
//						}else{
//							imag_sex.setBackgroundResource(R.drawable.img_female);
//						}
//						tv_mobile.setText(mobile);
//						tv_bumen.setText(homeContactDetailEntity.getFamily_name());
//						if("".equals(homeContactDetailEntity.getJob_name())){
//							tv_job.setText("暂无职位");
//						}else{
//							tv_job.setVisibility(View.VISIBLE);
//							tv_job.setText(homeContactDetailEntity.getJob_name());
//						}
//						String uri = homeContactDetailEntity.getAvatar();
//						imageLoader.displayImage(uri, imag_touxiang, options);
//					}
//
//					@Override
//					public void onFailed(String Message) {
//						hideLoading();
//						ToastHelper.showMsg(HomeContactDeail2Activity.this,
//								Message, false);
//						finish();
//					}
//				});
//	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.home_contact_deail2, menu);
		return true;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.lay_tel:
		case R.id.ivbtn_sms:
			if (homeContactDetailEntity != null
					&& homeContactDetailEntity.getMobile() != null) {
				Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"
						+ homeContactDetailEntity.getMobile()));
				startActivity(intent);
			}
			break;
		case R.id.btn_liaotian:
			SharedPreferences sp = getSharedPreferences("a.xml", 0);
			String realname = sp.getString("realname", "");
			String text = tv_name.getText().toString();
			if (text.equals(realname)) {
				Toast.makeText(this, "不能和自己聊天", Toast.LENGTH_SHORT).show();
			} else {
				if (homeContactDetailEntity != null) {
					chat();
				} else {
					Toast.makeText(HomeContactDeail2Activity.this,
							"未获取到联系人详情！", Toast.LENGTH_SHORT).show();
				}
			}
			break;
		case R.id.lay_setxinbiao:
			if (homeContactDetailEntity != null) {
				String is_favorite = homeContactDetailEntity.getIs_favorite();
				if("1".equals(is_favorite)){
					deleteContactFavorite();
				}else{
					putContactFavorite();
				}
			} else {
				Toast.makeText(HomeContactDeail2Activity.this, "未获取到联系人详情！",
						Toast.LENGTH_SHORT).show();
			}
			break;
		case R.id.lin_back:
			finish();
			break;
		case R.id.imageview001:
//			imag_touxiang.setDrawingCacheEnabled(true);
//			Bitmap bitmapCache = Bitmap.createBitmap(imag_touxiang.getDrawingCache());
//			imag_touxiang.setDrawingCacheEnabled(false);
//			Intent intent = new Intent(HomeContactDeail2Activity.this, ZoomActivity.class);
//			intent.putExtra("bitmap", bitmapCache);
//			startActivity(intent);
			String uri = com.magicsoft.constant.Constant.photourl + uid;
			Intent imageIntent = new Intent(HomeContactDeail2Activity.this,
					ImageViewZoomActivity.class);
			imageIntent.putExtra("imageurl", uri);
			startActivity(imageIntent);
			break;
		case R.id.lay_mybumen:
			Intent intent = new Intent(HomeContactDeail2Activity.this, HomeContactOrgActivity.class);
			RecentPerson recentPerson = new RecentPerson();
			recentPerson.setUid(familyid);
			recentPerson.setName(familyname);
			recentPerson.setType("org");
			intent.putExtra("homeContactOrgEntity", recentPerson);
			startActivity(intent );
			break;
		default:
			break;
		}

	}
	
	/**
	 * 添加星标
	 */
	private void putContactFavorite() {

		
		String contactsID = homeContactDetailEntity.getUid();

		if (contactService == null) {
			contactService = new ContactService(getApplicationContext());
		}

		contactService.putContactFavorite(yonghuID, uid,
				new GetOneRecordListener<String>() {

					@Override
					public void onFinish(String data) {
						homeContactDetailEntity.setIs_favorite("1");
						imag_xingbiao.setSelected(true);
						Intent intent = new Intent();
						intent.setAction("AddXingbiao");
						sendBroadcast(intent);
						ToastHelper.showMsg(HomeContactDeail2Activity.this,"添加成功", false);
					}

					@Override
					public void onFailed(String Message) {
						ToastHelper.showMsg(HomeContactDeail2Activity.this,
								Message, false);
					}
				});
	}

	/**
	 * 取消星标
	 */
	private void deleteContactFavorite() {

		if (contactService == null) {
			contactService = new ContactService(getApplicationContext());
		}

		contactService.deleteContactFavorite(yonghuID, uid,
				new GetOneRecordListener<String>() {

					@Override
					public void onFinish(String data) {
						homeContactDetailEntity.setIs_favorite("2");
						imag_xingbiao.setSelected(false);
						Intent intent = new Intent();
						intent.setAction("ShanchuXingbiao");
						sendBroadcast(intent);
						ToastHelper.showMsg(HomeContactDeail2Activity.this,"取消成功", false);
					}

					@Override
					public void onFailed(String Message) {
						ToastHelper.showMsg(HomeContactDeail2Activity.this,
								Message, false);
					}
				});
	}

//	private void contactDeailSettingMore() {
//		Intent intent = new Intent(this, ContactDeailSettingActivity.class);
//		intent.putExtra("uid", uid);
//		startActivity(intent);
//	}

	private void chat() {

		progressShow = true;
		final ProgressDialog pd = new ProgressDialog(this);
		pd.setCanceledOnTouchOutside(false);
		pd.setOnCancelListener(new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				progressShow = false;
			}
		});
		pd.setMessage(getString(R.string.Is_landing));
		pd.show();

		final long start = System.currentTimeMillis();
		SharedPreferences sp = getSharedPreferences("a.xml", 0);
		String username = sp.getString("username", "18030095903");
		String mima = "" + username.substring(5, username.length());

		EMChatManager.getInstance().login(username, mima, new EMCallBack() {

			@Override
			public void onSuccess() {
				if (!progressShow) {
					return;
				}

				try {
					// ** manually load all local groups and
					EMGroupManager.getInstance().loadAllGroups();
					EMChatManager.getInstance().loadAllConversations();
					initializeContacts();
					asyncFetchContactsFromServer();
				} catch (Exception e) {
					e.printStackTrace();
					runOnUiThread(new Runnable() {
						public void run() {
							pd.dismiss();
							ColorHolderApplication.getInstance().logout(null);
							Toast.makeText(getApplicationContext(),
									R.string.login_failure_failed, 1).show();
						}
					});
					return;
				}
				boolean updatenick = EMChatManager.getInstance()
						.updateCurrentUserNick(
								ColorHolderApplication.currentUserNick.trim());
				if (!updatenick) {
				}
				if (!isFinishing() && pd.isShowing()) {
					pd.dismiss();
				}
				Intent intent = new Intent(HomeContactDeail2Activity.this,
						ChatActivity.class);
				if (homeContactDetailEntity != null) {
					intent.putExtra("userId", mobile);
					intent.putExtra("contactID", uid);
					intent.putExtra("chatpeople", realname);
					intent.putExtra("back", "返回");
					startActivity(intent);
//					finish();
				}
			}

			private void asyncFetchContactsFromServer() {

				HXSDKHelper.getInstance().asyncFetchContactsFromServer(
						new EMValueCallBack<List<String>>() {

							@Override
							public void onSuccess(List<String> usernames) {
								Context context = HXSDKHelper.getInstance()
										.getAppContext();

								System.out.println("----------------"
										+ usernames.toString());
								EMLog.d("roster",
										"contacts size: " + usernames.size());
								Map<String, User2> userlist = new HashMap<String, User2>();
								for (String username : usernames) {
									User2 user = new User2();
									user.setUsername(username);
									setUserHearder(username, user);
									userlist.put(username, user);
								}
								User2 newFriends = new User2();
								newFriends
										.setUsername(Constant.NEW_FRIENDS_USERNAME);
								String strChat = context
										.getString(R.string.Application_and_notify);
								newFriends.setNick(strChat);

								userlist.put(Constant.NEW_FRIENDS_USERNAME,
										newFriends);
								User2 groupUser = new User2();
								String strGroup = context
										.getString(R.string.group_chat);
								groupUser.setUsername(Constant.GROUP_USERNAME);
								groupUser.setNick(strGroup);
								groupUser.setHeader("");
								userlist.put(Constant.GROUP_USERNAME, groupUser);

								User2 chatRoomItem = new User2();
								String strChatRoom = context
										.getString(R.string.chat_room);
								chatRoomItem.setUsername(Constant.CHAT_ROOM);
								chatRoomItem.setNick(strChatRoom);
								chatRoomItem.setHeader("");
								userlist.put(Constant.CHAT_ROOM, chatRoomItem);

								ColorHolderApplication.getInstance()
										.setContactList(userlist);
								UserDao dao = new UserDao(context);
								List<User2> users = new ArrayList<User2>(
										userlist.values());
								dao.saveContactList(users);

								HXSDKHelper.getInstance()
										.notifyContactsSyncListener(true);

								if (HXSDKHelper.getInstance()
										.isGroupsSyncedWithServer()) {
									HXSDKHelper.getInstance()
											.notifyForRecevingEvents();
								}

							}

							@Override
							public void onError(int error, String errorMsg) {
								HXSDKHelper.getInstance()
										.notifyContactsSyncListener(false);
							}

						});

			}

			private void setUserHearder(String username, User2 user) {
				String headerName = null;
				if (!TextUtils.isEmpty(user.getNick())) {
					headerName = user.getNick();
				} else {
					headerName = user.getUsername();
				}
				if (username.equals(Constant.NEW_FRIENDS_USERNAME)) {
					user.setHeader("");
				} else if (Character.isDigit(headerName.charAt(0))) {
					user.setHeader("#");
				} else {
					user.setHeader(HanziToPinyin.getInstance()
							.get(headerName.substring(0, 1)).get(0).target
							.substring(0, 1).toUpperCase());
					char header = user.getHeader().toLowerCase().charAt(0);
					if (header < 'a' || header > 'z') {
						user.setHeader("#");
					}
				}
			}

			private void initializeContacts() {
				Map<String, User2> userlist = new HashMap<String, User2>();
				User2 newFriends = new User2();
				newFriends.setUsername(Constant.NEW_FRIENDS_USERNAME);
				String strChat = getResources().getString(
						R.string.Application_and_notify);
				newFriends.setNick(strChat);

				userlist.put(Constant.NEW_FRIENDS_USERNAME, newFriends);
				User2 groupUser = new User2();
				String strGroup = getResources().getString(R.string.group_chat);
				groupUser.setUsername(Constant.GROUP_USERNAME);
				groupUser.setNick(strGroup);
				groupUser.setHeader("");
				userlist.put(Constant.GROUP_USERNAME, groupUser);
				ColorHolderApplication.getInstance().setContactList(userlist);
				UserDao dao = new UserDao(HomeContactDeail2Activity.this);
				List<User2> users = new ArrayList<User2>(userlist.values());
				dao.saveContactList(users);

			}

			@Override
			public void onProgress(int progress, String status) {
			}

			@Override
			public void onError(final int code, final String message) {
				if (!progressShow) {
					return;
				}
				runOnUiThread(new Runnable() {
					public void run() {
						pd.dismiss();
						Toast.makeText(getApplicationContext(),
								getString(R.string.Login_failed) + message,
								Toast.LENGTH_SHORT).show();
					}
				});
			}
		});
	}

	@Override
	public void backClicked() {
		if (isShowingLoading()) {
			hideLoading();
		} else {
			setResult(RESULT_OK);
			isBackAllowed = true;
		}
	}

}
